import 'package:flutter/material.dart';

import 'package:scrollview_exposure_tracker/scrollview_exposure_tracker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('测试')),
        body: ScrollviewExposureTracker(
          onExposure: (index) {
            print('Item $index is exposed');
          },
          onDisappear: (index) {
            print('Item $index has disappeared');
          },
          //listview
          builder: (scrollController, itemKeys) {
            return ListView.builder(
              controller: scrollController, // 将ScrollController赋值给ListView
              itemCount: 50,
              itemBuilder: (context, index) {
                // 为每个子组件分配一个GlobalKey
                if (!itemKeys.containsKey(index)) {
                  itemKeys[index] = GlobalKey();
                }
                return ListTile(
                  key: itemKeys[index], // 使用GlobalKey
                  title: Text('Item $index'),
                );
              },
            );
          },
          //gridview
          // builder: (scrollController, itemKeys) {
          //   return GridView.builder(
          //     controller: scrollController, // 将ScrollController赋值给GridView
          //     gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          //       crossAxisCount: 4, // 每行显示2个item
          //       childAspectRatio: 1.5, // 子组件的宽高比
          //     ),
          //     itemCount: 100,
          //     itemBuilder: (context, index) {
          //       // 为每个子组件分配一个GlobalKey
          //       if (!itemKeys.containsKey(index)) {
          //         itemKeys[index] = GlobalKey();
          //       }
          //       return Card(
          //         key: itemKeys[index], // 使用GlobalKey
          //         child: Center(
          //           child: Text('Item $index'),
          //         ),
          //       );
          //     },
          //   );
          // },
        ),
      ),
    );
  }
}
